package cn.aohan.scheduled.config;

import cn.aohan.scheduled.regiest.AnnotationScheduledJobRegister;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

/**
 * @author 傲寒
 */
@Configuration
@ComponentScan("cn.aohan")
@ConditionalOnProperty(name = "aohan.scheduled.enable", havingValue = "true", matchIfMissing = true)
public class AohanSchedulingConfiguration {

    private static final String QUARTZ_SCHEDULER_INSTANCE_NAME_KEY = "org.quartz.scheduler.instanceName";
    private static final String CONFIG_FILE_NAME = "quartz.properties";

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private ConfigurableEnvironment env;

    /**
     * 已计划注册批注
     *
     * @return {@link AnnotationScheduledJobRegister}
     */
    @Bean
    public AnnotationScheduledJobRegister registerAnnoScheduled(Scheduler scheduler) {
        return new AnnotationScheduledJobRegister(scheduler);
    }

    /**
     * 本地调度程序工厂bean
     *
     * @return {@link SchedulerFactoryBean}
     * @throws IOException ioexception
     */
    @Bean(value = "schedulerFactoryBean")
    public SchedulerFactoryBean schedulerFactoryBeanForLocal() throws IOException {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setStartupDelay(5);
        Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(CONFIG_FILE_NAME));
        // Replace placeholders with actual values from environment
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            String resolvedValue = env.resolvePlaceholders(value);
            properties.setProperty(key, resolvedValue);
        }
        String schedulerInstanceName = (String) properties.get(QUARTZ_SCHEDULER_INSTANCE_NAME_KEY);
        String instanceName = StringUtils.isNotBlank(schedulerInstanceName) ? schedulerInstanceName : applicationName;
        schedulerFactoryBean.setSchedulerName(instanceName);
        schedulerFactoryBean.setQuartzProperties(properties);
        return schedulerFactoryBean;
    }

}
